<?php

/**
 * @desc		路由匹配分发类
 * ---------------------------------------------------------------------
 * @author	unphp <unphp@qq.com>
 * @date		2014-03-05
 * @copyright	UnPHP 1.1
 * ---------------------------------------------------------------------
 */
namespace UnPHP\Core;

class Router
{

        private $_routes = array();
        private $_current_route = null;

        /**
         * 注册路由规则
         * @author Xiao Tangren  <unphp@qq.com>
         * @data 2014-03-05
         */
        public function addRoute($name, RouteInterface $route)
        {
                $this->_routes[$name] = $route;
        }

        /**
         * 注册路由规则
         * @author Xiao Tangren  <unphp@qq.com>
         * @data 2014-03-05
         */
        public function getRegisteredRoute($name) 
        {
                return isset($this->_routes[$name]) ? $this->_routes[$name] : $this->_routes['default'];
        }

        /**
         * 开始路由匹配
         * @author Xiao Tangren  <unphp@qq.com>
         * @data 2014-03-05
         * @param UnPHP_Request_Abstract $request
         */
        public function route(RequestAbstract $request)
        {
                $rs = FALSE;
                $this->_routes['default'] = new RouteDefault();
                if (FALSE === $rs && !empty($this->_routes))
                {
                        // 遍历理由协议
                        foreach ($this->_routes as $name => $route)
                        {
                                if ($route->route($request))
                                {
                                        $this->_current_route = $name;
                                        $rs = TRUE;
                                        break;
                                }
                        }
                }
                return $rs;
        }

}

/**
 * “路由协议”接口
 * @system UNPHP 
 * @version UNPHP 1.0
 * @author Xiao Tangren  <unphp@qq.com>
 * @data 2014-03-05
 * */
Interface RouteInterface
{

        /**
         * 分析请求url，匹配路由规则。
         * @author Xiao Tangren  <unphp@qq.com>
         * @data 2014-03-05
         * return bool
         */
        public function route(RequestAbstract $request);
}
